package com.quanquan.user.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.quanquan.user.dto.IntegralRuleDTO;
import com.quanquan.user.entity.IntegralRule;
import com.quanquan.user.exception.UserLevelException;
import com.quanquan.user.repository.IntegralRuleRepository;
import com.quanquan.user.request.CustomDouble;
import com.quanquan.user.request.IntegralRuleRequestBody;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import utils.DateUtils;

import java.util.*;

/**
 * 功能描述:积分规则
 *
 * @ClassName: IntegralRuleService
 * @Author: xiaoqianh丶
 * @Date: 2019-05-07 16:35
 * @Version: V1.0
 */
@Service
public class IntegralRuleService {

    private final IntegralRuleRepository integralRuleRepository;
    private final RedisTemplate redisTemplate;
    private final CommercialDoubleService commercialDoubleService;

    @Autowired
    public IntegralRuleService(IntegralRuleRepository integralRuleRepository, RedisTemplate redisTemplate, CommercialDoubleService commercialDoubleService) {
        this.integralRuleRepository = integralRuleRepository;
        this.redisTemplate = redisTemplate;
        this.commercialDoubleService = commercialDoubleService;
    }

    public IntegralRule findIntegralRule() {
        List<IntegralRule> all = integralRuleRepository.findAll();
        IntegralRule integralRule = all.get(0);
        redisIntegralRuleDouble(integralRule);
        return integralRule;
    }

    private void redisIntegralRuleDouble(IntegralRule integralRule) {
        Boolean timeDouble = integralRule.getTimeDouble();
        Boolean memberBirthDayDouble = integralRule.getMemberBirthDayDouble();
        Boolean memberLevelDouble = integralRule.getMemberLevelDouble();
        Boolean storeCommercial = integralRule.getStoreCommercial();
        String birthDayDouble = integralRule.getBirthDayDouble();


        BoundHashOperations<String, String, Boolean> boundHashOperations = redisTemplate.boundHashOps("integralRule");
        boundHashOperations.put("timeDouble", timeDouble);
        boundHashOperations.put("memberBirthDayDouble", memberBirthDayDouble);
        boundHashOperations.put("memberLevelDouble", memberLevelDouble);
        boundHashOperations.put("storeCommercial", storeCommercial);

        //缓存生日积分翻倍倍数
        redisTemplate.opsForValue().set("birthDayDouble", birthDayDouble);
        //缓存时间段积分翻倍倍数
        if (timeDouble) {
            String timeDoubleNum = integralRule.getTimeDoubleNum();
            String startTime = integralRule.getStartTime();
            String endTime = integralRule.getEndTime();
            String integralTimeDouble = startTime + "," + endTime + "," + timeDoubleNum;
            redisTemplate.opsForValue().set("integralTimeDouble", integralTimeDouble);

        }
    }

    /**
     * 查看列表
     *
     * @return
     */
    public List<IntegralRuleDTO> list() {
        List<IntegralRuleDTO> integralRuleDTOS = new LinkedList<>();
        List<IntegralRule> integralRules = integralRuleRepository.integralRules();
        for (IntegralRule integralRule : integralRules) {
            IntegralRuleDTO integralRuleDTO = new IntegralRuleDTO();
            BeanUtils.copyProperties(integralRule, integralRuleDTO);
            integralRuleDTOS.add(integralRuleDTO);
        }
        return integralRuleDTOS;
    }

    /**
     * 通过id查详情
     *
     * @return
     */
    public IntegralRuleDTO findByIntegralRuleId(String id) {
        IntegralRule integralRule = integralRuleRepository.findByRuleId(id);
        if (integralRule == null) {
            return null;
        }
        IntegralRuleDTO integralRuleDTO = new IntegralRuleDTO();
        BeanUtils.copyProperties(integralRule, integralRuleDTO);

        //查询规则
        List<String> commercialIds = commercialDoubleService.queryCommercialId(integralRule.getId());
        if (commercialIds != null) {
            integralRuleDTO.setCommercialIds(commercialIds);
        }
        return integralRuleDTO;
    }

    public String updateIntegralRule(IntegralRuleRequestBody requestBody) throws UserLevelException {
        IntegralRule integralRule = integralRuleRepository.findByRuleId(requestBody.getId());
        if (integralRule == null) {
            throw new UserLevelException("积分规则不存在");
        }
        BeanUtil.copyProperties(requestBody, integralRule, true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        integralRule.setUpdateTime(DateUtils.dateToString(new Date(), DateUtils.TIMESTAMP));
        integralRuleRepository.saveAndFlush(integralRule);
        if (integralRule.getStoreCommercial()) {
            //创建业态翻倍规则
            commercialDoubleService.createCommercialDouble(requestBody.getCommercialIds(), integralRule.getId(), requestBody.getDoubleNum());
        }
        redisIntegralRuleDouble(integralRule);

        return "更新积分规则成功";
    }

    /**
     * 修改业态翻倍状态 (周三 0时 执行)
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void changeStatus() {
        //判断今天是否在8月31日之前
        Date nowTime = new Date();
        Date endTime = DateUtils.parseStr2Date("yyyy-MM-dd", "2019-08031");
        assert endTime != null;
        if (nowTime.before(endTime)) {
            List<IntegralRule> all = integralRuleRepository.findAll();
            IntegralRule integralRule = all.get(0);
            //先判断今天是不是星期三
            String week = getWeek();
            if(week.equals("星期三")){
                integralRule.setStoreCommercial(true);
                integralRuleRepository.save(integralRule);
                List<CustomDouble> customDoubles = new ArrayList<>();
                CustomDouble customDouble = new CustomDouble();
                customDouble.setMarkingRuleId("1b4c689eccf54ad6ae600b8bf6fc2be4");
                customDouble.setCommercialId("352c35c1682c4714b03787504832c964");
                customDouble.setNum(2);
                customDoubles.add(customDouble);

                CustomDouble customDouble1 = new CustomDouble();
                customDouble1.setMarkingRuleId("1b4c689eccf54ad6ae600b8bf6fc2be4");
                customDouble1.setCommercialId("e905cfe61c5a46f891d56cc463f4a359");
                customDouble1.setNum(3);
                customDoubles.add(customDouble1);
                commercialDoubleService.updateCommercialDouble(customDoubles);


            }else {
                integralRule.setStoreCommercial(false);
            }
            integralRuleRepository.save(integralRule);
            redisIntegralRuleDouble(integralRule);
        }else{
            System.out.println("活动已结束");
        }


    }

    private String getWeek() {
        String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        System.out.println(cal.get(Calendar.DAY_OF_WEEK));
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;

        }
        return weeks[week_index];

    }
}
